package com.haiziwang.yst.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
	
	public static String getLocalNetWorkIp() {
	    String localIp = "";
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (netInterfaces.hasMoreElements()) {// 遍历所有的网卡
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                if (ni.isLoopback() || ni.isVirtual()) {// 如果是回环和虚拟网络地址的话继续
                    continue;
                }
                Enumeration<InetAddress> addresss = ni.getInetAddresses();
                while (addresss.hasMoreElements()) {
                    InetAddress address = addresss.nextElement();
                    if (address instanceof Inet4Address) {// 这里暂时只获取ipv4地址
                        ip = address;
                        break;
                    }
                }
                if (ip != null) {
                    break;
                }
            }
            if (ip != null) {
                localIp = ip.getHostAddress();
            } else {
                localIp = "127.0.0.1";
            }
        } catch (Exception e) {
            localIp = "127.0.0.1";
        }
        return localIp;
    }
	
	public static String getClientIp(HttpServletRequest request) {
		String requestIp = "127.0.0.1";

		requestIp = request.getHeader("X-Real-IP");

		if (requestIp == null || requestIp.length() == 0 || "unknown".equalsIgnoreCase(requestIp)) {
			requestIp = request.getHeader("x-forwarded-for");
		}

		if (requestIp == null || requestIp.length() == 0 || "unknown".equalsIgnoreCase(requestIp)) {
			requestIp = request.getHeader("Proxy-Client-IP");
		}
		if (requestIp == null || requestIp.length() == 0 || "unknown".equalsIgnoreCase(requestIp)) {
			requestIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (requestIp == null || requestIp.length() == 0 || "unknown".equalsIgnoreCase(requestIp)) {
			requestIp = request.getRemoteAddr();
		}

		if ((null != requestIp) && (16 < requestIp.length())) {
			if (requestIp.indexOf(",") > 0) {
				requestIp = requestIp.substring(0, requestIp.indexOf(","));
			}
		}
		return requestIp;
	}
}
